import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * This class defines a crab. Crabs live on the beach.
 */
public class Crab extends Actor
{
    GreenfootImage image1 = new GreenfootImage("crab.png");
    GreenfootImage image2 = new GreenfootImage("crab2.png");
    int count = 0;
    public Crab(){
        setImage(image1);
    }
    
    /**
     * Act - do whatever the Crab wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        move(4);
        turnAtEdge();
        control();
        eat();
        animation();
        stop();
        switchImage();
    }
    
    public void switchImage() {
        if (getImage()==image1) {
            setImage(image2);
        }else{
            setImage(image1);
        }
    }
    
     public void eat() {
        if (isTouching(Worm.class)){
            removeTouching(Worm.class);
            count++;
            Greenfoot.playSound("slurp.wav");
            CrabWorld world = (CrabWorld)getWorld();
            world.drawNum(count);
            World w = getWorld();
            w.showText("吃 虫 数 "+count,500,500);
        }
    }
    
    public void stop() {
        if (count==4){
            Greenfoot.stop();
            World w = getWorld();
            GreenfootImage bg = w.getBackground();
            Font font = bg.getFont();
            font = font.deriveFont(100);
            bg.setFont(font);
            bg.setColor(Color.GREEN);
            bg.drawString("成功",150,300);
        }
    }

    public void turnAtEdge() {
        if (isAtEdge()) {
            turn(15);
        }
    }
 
    public void  control(){
        if (Greenfoot.isKeyDown("left")) {
            turn(-15);
        }
        if (Greenfoot.isKeyDown("right")) {
            turn(15);
        }
    }
    
    public void animation (){
        if (getImage() == image1){
            setImage(image2);
        }
        else{
            setImage(image1);
        } 
    }
}

    
